﻿using CoreDomain.BusinessCore;
using DomainService.IService;
using DomainService.IService.Sys;
using Infrastructure;
using Infrastructure.IRepository.Sys;
using Infrastructure.Repository.Sys;
using Model;
using Model.BusinessModel.InPut;
using Model.BusinessModel.OutPut;
using Model.BusinessModel.OutPut.sys;
using Model.DomainModel.Sys;
using Utility;
using Utility.Enum;

namespace DomainService.Service.Sys
{
    /// <summary>
    /// 公司服务接口实现
    /// </summary>
    public class SysCorporationService : ISysCorporationService
    {
        #region 构造实例化

        /// <summary>
        /// 公司底层仓储
        /// </summary>
        private readonly ISysCorporationRepository _sysCorporationRepository;

        /// <summary>
        /// 基础服务
        /// </summary>
        private readonly IBaseService _baseService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sysCorporationRepository"></param>
        public SysCorporationService(ISysCorporationRepository sysCorporationRepository, IBaseService baseService)
        {
            _sysCorporationRepository = sysCorporationRepository;
            _baseService = baseService;
        }

        #endregion

        #region  业务逻辑

        /// <summary>
        /// 获取所有公司数据
        /// </summary>
        /// <returns></returns>
        public List<SysCorporationOutPut> GetAllCorporation(string? corporationKey)
        {
            var result = _baseService.GetAuthWhere(RuleTypeEnum.DataRowRule, "sc");
            string? authWhere = string.Empty;
            if (result.success) { authWhere = result.data[0]; }
            else
                ExceptionHelper.ThrowBusinessException(result.msg);
            var corporationList = _sysCorporationRepository.GetAllCorporation(corporationKey, authWhere);
            return corporationList;
        }

        /// <summary>
        /// 获取所有公司
        /// </summary>
        /// <param name="corporationKey">公司key</param>
        /// <returns></returns>
        public List<SelectOutPut> GetAll(string? corporationKey)
        {
            List<SelectOutPut> selectOutPuts = [];
            var list = _sysCorporationRepository.GetAllCorporation(corporationKey);
            foreach (var item in list)
            {
                SelectOutPut selectOutPut = new()
                {
                    value = item.CorporationKey ?? string.Empty,
                    label = item.CorporationName ?? string.Empty,
                    disabled = item.IsOpen==true?false:true,
                };
                selectOutPuts.Add(selectOutPut);
            }
            return selectOutPuts;
        }

        /// <summary>
        ///  获取公司下的系统
        /// </summary>
        /// <returns></returns>
        public List<TreeOutPut> GetCorporationSystemList()
        {
            var corporationSystemList = _sysCorporationRepository.GetCorporationSystemList();
            var tree = corporationSystemList.ConvertTreeData();
            return tree;
        }

        /// <summary>
        /// 新增公司
        /// </summary>
        /// <param name="sysCorporation">公司数据</param>
        public ReceiveStatus Insert(SysCorporation sysCorporation)
        {
            ReceiveStatus receiveStatus = new();
            sysCorporation.CorporationKey = Guid.NewGuid().ToString();
            var result = Validate(sysCorporation);
            if (!result.success)
                return result;
            _sysCorporationRepository.Insert(sysCorporation, BaseSqlRepository.sysCorporation_insertSql);
            return receiveStatus;
        }

        /// <summary>
        /// 修改公司
        /// </summary>
        /// <param name="sysCorporation">公司数据</param>
        public ReceiveStatus Update(SysCorporation sysCorporation)
        {
            ReceiveStatus receiveStatus = new();
            var model = _sysCorporationRepository.GetByKey(sysCorporation.CorporationKey.ToString(), BaseSqlRepository.sysCorporation_selectByKeySql);
            if (model == null)
                return ExceptionHelper.CustomException(string.Format("公司名称【{0}】不存存在或已删除!", sysCorporation.CorporationName));
            var result = Validate(sysCorporation);
            if (!result.success)
                return result;

            if (sysCorporation.CorporationKey == Const.XC_CorporationKey)
            {
                return ExceptionHelper.CustomException(string.Format("公司【{0}】为演示公司，禁止操作。", model.CorporationName));
            }
            _sysCorporationRepository.Update(sysCorporation, BaseSqlRepository.sysCorporation_updateSql);
            return receiveStatus;
        }

        /// <summary>
        /// 设置公司是否启用
        /// </summary>
        /// <param name="updateCorporationIsOpenInPut">修改模型</param>
        public ReceiveStatus SetCorporationIsOpen(UpdateIsOpenInPut updateCorporationIsOpenInPut)
        {
            ReceiveStatus receiveStatus = new();
            if (updateCorporationIsOpenInPut == null)
                return ExceptionHelper.CustomException("请选择公司");
            if (updateCorporationIsOpenInPut.Keys.Count == 0)
                return ExceptionHelper.CustomException("请选择公司");

            var corporationKey = updateCorporationIsOpenInPut.Keys.FirstOrDefault(f => f == Const.XC_CorporationKey);
            if (!string.IsNullOrWhiteSpace(corporationKey))
            {
                var model = _sysCorporationRepository.GetByKey(corporationKey, BaseSqlRepository.sysCorporation_selectByKeySql);
                return ExceptionHelper.CustomException(string.Format("公司【{0}】为演示公司，禁止操作。", model.CorporationName));
            }


            //写入数据库，加入事务
            TransactionHelper.ExecuteTransaction(() =>
            {
                _sysCorporationRepository.SetCorporationIsOpen(updateCorporationIsOpenInPut.Keys, updateCorporationIsOpenInPut.IsOpen);
            });

            return receiveStatus;
        }

        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="sysCorporation"></param>
        /// <returns></returns>
        public ReceiveStatus Validate(SysCorporation sysCorporation)
        {
            ReceiveStatus receiveStatus = new ReceiveStatus();
            /*
            新增/修改前验证
            1、公司的名称和编码不能出现重复
            2、公司名称和编码不能为空
            */

            if (string.IsNullOrWhiteSpace(sysCorporation.CorporationName))
                return ExceptionHelper.CustomException("公司名称不能为空!");
            if (string.IsNullOrWhiteSpace(sysCorporation.CorporationCode))
                return ExceptionHelper.CustomException("公司编码不能为空!");

            var corporationList = _sysCorporationRepository.GetCorporationMsg(sysCorporation.CorporationName, sysCorporation.CorporationCode);
            foreach (var item in corporationList)
            {
                if (sysCorporation.CorporationName.ToLower() == item.CorporationName.ToLower() && sysCorporation.CorporationKey != item.CorporationKey)
                    return ExceptionHelper.CustomException(string.Format("公司名称【{0}】已存在,请重新输入", sysCorporation.CorporationName));
                if (sysCorporation.CorporationCode.ToLower() == item.CorporationCode.ToLower() && sysCorporation.CorporationKey != item.CorporationKey)
                    return ExceptionHelper.CustomException(string.Format("公司编码【{0}】已存在,请重新输入", sysCorporation.CorporationCode));
            }
            return receiveStatus;
        }
        #endregion
    }
}
